<?php
namespace Admin\Controller;
class NodeController extends BaseController{

    private $_mod; //模型
    private $node; //节点树

    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D("Node"); //获得模型实例
        $data = $this->_mod->order('list_order ASC, nid ASC')->select();
        $node = \Common\Lib\Tool\Data::tree($data, "title", "nid", "pid");
        $this->node = $node;
    }

    //节点列表
    public function index()
    {
        $this->assign('node', $this->node);
        $this->display();
    }

    //添加节点
    public function add()
    {
        if (IS_POST) {
            if ($this->_mod->addNode()) {
                $this->success('添加成功');
            } else {
                $this->error($this->_mod->getError());
            }
        } else {
            //配置菜单列表
            $this->assign('node', $this->node);
            $this->assign('res', null);
            $this->assign('pid', I('pid'));
            $this->display('edit');
        }
    }

    //删除节点
    public function del()
    {
        if ($this->_mod->delNode()) {
            $this->success('删除成功');
        } else {
            $this->error($this->_mod->getError());
        }
    }

    //修改节点
    public function edit()
    {
        if (IS_POST) {
            if ($this->_mod->editNode()) {
                $this->success('修改成功');
            } else {
                $this->error($this->_mod->getError());
            }
        } else {
            $nid = I('nid');
            $res = $this->_mod->find($nid);
            foreach ($this->node as $id => $node) {
                $this->node[$id]['disabled'] = \Common\Lib\Tool\Data::isChild($this->node, $id, $nid, 'nid') ? ' disabled="disabled" ' : '';
            }
            $this->assign('node', $this->node);
            $this->assign('res',$res);
            $this->assign('pid', $res['pid']);
            $this->display();
        }
    }

    //更改菜单排序
    public function updateOrder()
    {
        $menu_order = I("post.list_order");
        foreach ($menu_order as $nid => $order) {
            $this->_mod->save(array(
                "nid" => $nid,
                "list_order" => $order
            ));
        }
        $this->success('更改排序成功');
    }

    /**
     * 设置状态
     * @return string
     */
    public function setStatus()
    {
        parent::setStatus( $this->_mod, 'is_show' );
    }
}